package com.block.test.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.block.common.bean.CommonParam;
import com.block.common.bean.PageParam;
import com.block.common.bean.SessionBean;
import com.block.common.util.HttpReturnUtil;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.AppEncrypt;
import com.block.test.factory.ReqValidateFactory;
import com.block.test.service.IValidateService;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 参数校验拦截器
 */
public class ParamValidateInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = (String) request.getAttribute("uri");
        CommonParam commonParam = (CommonParam) request.getAttribute("commonParam");
        JSONObject transData = (JSONObject) request.getAttribute("tranData");
        SessionBean sessionBean = (SessionBean) request.getAttribute("sessionBean");
        AppEncrypt appEncrypt = (AppEncrypt) request.getAttribute("appEncrypt");
        Date date = (Date) request.getAttribute("startDate");

        ResponseVo responseVo = null;
        // 处理分页数据
        responseVo = pageParamProcess(request, transData);
        if (responseVo != null){
            HttpReturnUtil.returnJson(response, appEncrypt, responseVo, date, uri);
            return false;
        }

        IValidateService validateService = ReqValidateFactory.getValidateService(uri);
        if (validateService == null) {
            return true;
        }
        responseVo = validateService.handleProcess(request, transData,sessionBean);
        if (responseVo == null) {
            return true;
        }
        HttpReturnUtil.returnJson(response, appEncrypt, responseVo, date, uri);
        return false;
    }

    /**
     * 统一处理分页数据
     * 分页数据不正确，则返回ResponseVo对象
     * 正确，返回null，不进行处理
     * @param request
     * @param tranData
     * @return
     */
    public ResponseVo pageParamProcess(HttpServletRequest request, JSONObject tranData){
        /**
         * 如果有分页信息，统一判断分页信息
         */
        Integer pageNo = tranData.getInteger("pageNo");
        Integer pageNum = tranData.getInteger("pageNum");

        if (ObjectUtil.isEmpty(pageNo)){
            pageNo = 1;
        }

        if (ObjectUtil.isEmpty(pageNum)){
            pageNum = 20;
        }

        // 如果有分页需求，直接获取即可
        request.setAttribute("pageParam", new PageParam(pageNo, pageNum));
        return null;
    }
}
